<template>
  <div class="container">
    <div class="to-register-container">
      <div class="left" :style="{'background-image': 'url(' + currentSideUrl + ')'}"/>
      <div class="right" v-loading="loading" element-loading-text="注册账号中...">
        <el-header class="welcome">欢迎注册<a style="color: #ff31a3">信服通</a></el-header>
        <el-header class="header">责任胜于天，安全在心间！</el-header>
        <el-form ref="refRegisterForm" :model="registerForm" class="registerForm" :rules="verifyRules">
          <el-form-item prop="username">
            <el-input
                ref="username"
                v-model="registerForm.username"
                placeholder="用户名"
                name="username"
                type="text"
                auto-complete="on"></el-input>
          </el-form-item>
          <el-form-item prop="nickname">
            <el-input
                ref="nickname"
                v-model="registerForm.nickname"
                placeholder="中文名"
                name="nickname"
                type="text"
                auto-complete="on"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
                ref="password"
                v-model="registerForm.password"
                placeholder="密码"
                name="password"
                type="text"
                show-password
                auto-complete="on"></el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
                ref="confirmPassword"
                v-model="registerForm.confirmPassword"
                placeholder="请再次输入密码"
                name="confirmPassword"
                type="text"
                show-password
                auto-complete="on"></el-input>
          </el-form-item>
          <el-form-item prop="loginphone">
            <el-input
                ref="loginphone"
                v-model="registerForm.loginphone"
                placeholder="手机号码"
                name="loginphone"
                type="text"
                auto-complete="on"></el-input>
          </el-form-item>
          <el-form-item prop="sharecode">
            <el-input
                ref="sharecode"
                v-model="registerForm.sharecode"
                placeholder="有效邀请码"
                name="sharecode"
                type="text"
                auto-complete="on"></el-input>
          </el-form-item>
          <el-button :loading="loading" type="primary" style="width:100%;margin-top:20px;"
                     @click.prevent="handleRegister(refRegisterForm)">立即注册</el-button>
        </el-form>
        <el-popover content="点击切换界面" trigger="hover" placement="top-start">
          <template #reference>
            <svg-icon class="setting" name="gear-fill" size="30" @click="switchCode"></svg-icon>
          </template>
        </el-popover>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, onMounted, reactive, ref} from "vue";
import {Utils} from "@/utils/utils";
import {validContactPhone} from "@/utils/validate";
import {IRegister} from "@/iwb/IUser";
import {FormInstance, FormRules} from "element-plus";
import {useUserStore} from "@/store/user";
import TabBtn from "@/layout/TabBtn.vue";
import {DialogUtils} from "@/utils/DialogUtils";
import {Md5Utils} from "@/utils/Md5Utils";

export default defineComponent({
  name: "toRegister",
  components: {TabBtn},
  setup(props, context) {
    const loading = ref(false);
    const currentSideUrl = ref('static/register-1.jpg');
    const validateContact = (rule: any, value: string, callback: any) => {
      if (!validContactPhone(value) || value.length !== 11) {
        callback(new Error('请输入正确的手机号'))
      }  else {
        callback();
      }
    };
    const validateUsername = (rule: any, vaule: string, callback: any) => {
      const zg = /^[0-9a-zA-Z]+$/;
      //const zg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]*$/;
      if (zg.test(vaule)) {
        callback();
      } else {
        callback(new Error('请输入数字和字母组合的用户名'));
      }
    }
    const validatePassword = (rule: any, value: string, callback: any) => {
      if (registerForm.value.password === value) {
        callback()
      } else {
        callback(new Error('两次输入的密码不相同'));
      }
    }
    const index = ref(0);
    const urls = ref([
      'static/register-1.jpg',
      'static/register-2.jpg',
      'static/register-3.jpg',
      'static/register-4.jpg'
    ])

    const playPicture = () => {
      setInterval(() => {
        index.value += 1;
        index.value %= 4;
        currentSideUrl.value = urls.value[index.value];
      }, 5000)
    }

    const registerForm = ref({} as IRegister);
    const refRegisterForm = ref<FormInstance>();

    const verifyRules = reactive<FormRules>({
      username: [{required: true, trigger: 'blur', validator: validateUsername}],
      nickname: [{required: true, trigger: 'blur', message: '请输入中文名'}],
      password: [{required: true, trigger: 'blur', message: '请输入密码'}],
      confirmPassword: [{required: true, trigger: 'blur', validator: validatePassword}],
      loginphone: [{required: true, trigger: 'blur', validator: validateContact}],
      sharecode: [{required: true, trigger: 'blur', message: '请输入有效邀请码'}]
    })

    const handleRegister = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      const userStore = useUserStore();
      formEl.validate((valid: boolean, fields) => {
        if (valid) {
          loading.value = true;
          const formData: IRegister = Utils.cloneObject(registerForm.value);
          const password = registerForm.value.password;
          formData.password = Md5Utils.b64MD5(password);
          userStore.toRegister(formData).then(res => {
            DialogUtils.showWarningBox("温馨提示", "注册成功，请跳转到登录界面！");
            loading.value = false;
          }).catch(error=>{
            console.error(error);
            loading.value = false;
          })
        } else {
          loading.value = false
          console.log('error submit!!', fields);
          return false
        }
      });
    };

    const switchCode = () => {
      context.emit('switchCode');
    }

    onMounted(() => {
      playPicture();
    })

    return {
      refRegisterForm,
      loading,
      currentSideUrl,
      registerForm,
      verifyRules,
      handleRegister,
      switchCode
    }
  }
})
</script>

<style scoped lang="scss">
@import "src/styles/variable";
.to-register-container {
  margin: 0;
  height: 100%;
  width: 100%;
  display: grid;
  justify-content: center;
  align-content: center;
  grid-template-columns: 1fr 1fr;
  -webkit-user-select: none;
  -webkit-app-region: drag; // 可拖动
  grid-template-rows: 100%;
  background-color: $color-background-base;

  .left {
    margin: auto;
    height: 100%;
    width: 100%;
    overflow: hidden;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    border-bottom-left-radius: 10px;
    border-top-left-radius: 10px;
  }

  .right {
    margin: 20px;
    display: flex;
    flex-direction: column;
    -webkit-app-region: drag; // 可拖动
    justify-content: center;
    vertical-align: middle;
    align-items: center;
  }

  .welcome {
    top: 0;
    right: 0;
    font-size: 41px;
  }
  .header {
    font-size: 28px;
    line-height: 1.2;
    color: $color-sub-text-base
  }
  .registerForm {
    -webkit-app-region: no-drag; // 不可拖动
    width: 100%;
  }
  :deep(.loginForm) {
    .el-autocomplete {
      position: relative;
      display: block;
      width: 100%;
    }
  }
  .footer-text {
    -webkit-app-region: no-drag; // 不可拖动
    display: flex;
    justify-content: space-between;
    padding: 5px 50px 0 25px;
    z-index: 0;
  }
  .setting {
    position: fixed;
    right: 10px;
    bottom: 10px;
    outline: none;
  }
}
</style>
